<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    >
    </van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="loading">
        <van-loading
          color="#3296fa"
          vertical
        >加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="articleInfo.title">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ articleInfo.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="articleInfo.aut_photo"
          />
          <div slot="title" class="user-name">{{ articleInfo.aut_name}}</div>
          <div slot="label" class="publish-date">{{articleInfo.pubdate | relativeTime}}</div>
          <!-- 关注功能组件 -->
          <!-- $event是模板中的事件参数 -->
          <!-- 在组件上使用v-model（父组件既想向子组件传值，子组件又想改变父组件传的值） -->
          <followUser
          class="follow-btn"
          :userID="articleInfo.aut_id"
          v-model="articleInfo.is_followed"
          ></followUser>
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div ref="articleContent" class="article-content markdown-body" v-html="articleInfo.content"></div>
        <van-divider>正文结束</van-divider>

        <!-- 文章评论 -->
        <commentList :target="articleInfo.art_id" :list="list" @commentCount="allCount = $event" @replyComment="onReply"></commentList>
      </div>
      <!-- /加载完成-文章详情 -->
      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="errStatus === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <!-- 点击后重新加载 -->
        <van-button class="retry-btn" @click="getArticle()">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>
    <!-- 底部区域 -->
    <div class="article-bottom" v-if="articleInfo.title">
      <van-button
        class="comment-btn"
        type="default"
        round
        size="small"
        @click="popupIsSHOW = true"
      >写评论</van-button>
      <van-icon
        name="comment-o"
        :badge="allCount"
        color="#777"
      />
      <!-- 收藏功能组件 -->
     <collectArticle :artID="articleInfo.art_id" v-model="articleInfo.is_collected"></collectArticle>
     <likeArticle v-model="articleInfo.attitude" :artID="articleInfo.art_id"></likeArticle>
      <van-icon name="share" color="#777777"></van-icon>
    </div>
    <!-- /底部区域 -->
    <!-- 评论文章 -->
    <van-popup v-model="popupIsSHOW" position="bottom">
      <addComment :list="list"  @addComment="addComment"></addComment>
    </van-popup>
    <!-- 回复评论 -->
    <van-popup v-model="replyIsSHOW" position="bottom" :style="{ height: '100%' }">
      <!-- 弹层关闭让组件销毁，保证每次渲染都是最新的内容 -->
      <replyComment v-if="replyIsSHOW" :currentComment="comment" @close="replyIsSHOW = false"></replyComment>
    </van-popup>
  </div>
</template>

<script>
// 获取文章详情接口
import { getArticleInfo } from '@/api/article'
// 关注功能组件
import followUser from '@/components/follow-user'
// 收藏功能组件
import collectArticle from '@/components/collectArticle'
// 点赞功能组件
import likeArticle from '@/components/likeArticle'
// 评论列表组件
import commentList from '@/views/article/components/commentList'
// 评论弹出框
import addComment from '@/views/article/components/addComment'
// 评论列表
import replyComment from '@/views/article/components/replyComment'
// 图片预览
import { ImagePreview } from 'vant'

export default {
  name: 'ArticleIndex',
  components: {
    followUser, // 关注功能组件
    collectArticle, // 收藏功能组件
    likeArticle,
    commentList,
    addComment,
    replyComment
  },
  props: {
    articleID: {
      type: [Number, String, Object],
      required: true
    }
  },
  provide () {
    return {
      articleID: this.articleID
    }
  },
  data () {
    return {
      articleInfo: {}, // 存储文章详情
      loading: true, // 控制加载状态的显示
      errStatus: 0, // 失败状态码
      list: [], // 评论列表
      allCount: 0, // 总获赞数
      popupIsSHOW: false, // 控制文章弹出层显示隐藏
      replyIsSHOW: false, // 控制回复评论弹出层的显示隐藏
      comment: {} // 包含评论信息的对象
    }
  },
  created () {
    this.getArticle()
  },
  methods: {
    // 获取文章信息
    async getArticle () {
      // 每次加载前让加载中重新展示
      this.loading = true
      try {
        const { data } = await getArticleInfo(this.articleID)
        this.articleInfo = data.data
        // 初始化图片点击节点
        // 在数据更新后立即拿不到,异步拿到真实dom
        setTimeout(() => { // 在这里能拿到真实的dom
          this.imgPreview()
        }, 0)
      } catch (err) {
        if (err.response && err.response.status === 404) {
          this.errStatus = 404
        } else {
          this.$toast('获取文章失败，请稍后再试')
        }
      }
      // 无论加载失败还是成功 都要关闭加载状态
      this.loading = false
    },
    // 点击图片预览
    imgPreview () {
      const articleContent = this.$refs.articleContent
      const imgs = articleContent.querySelectorAll('img')
      const images = []
      imgs.forEach((item, index) => {
        images.push(item.src)
        item.onclick = () => {
          ImagePreview({
            images, // 存储图片路径
            startPosition: index // 指定初始位置
          })
        }
      })
    },
    addComment (data) {
      // 关闭弹出层
      this.popupIsSHOW = false
      // 将最新评论放在最前边显示
      this.list.unshift(data)
      this.allCount++
    },
    onReply (comment) {
      this.replyIsSHOW = true
      this.comment = comment
    }
  }
}
</script>

<style scoped lang="less">
// 引入美化文章的样式
@import "./github-markdown.css";
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
